<template>
    <div class="producer-bg">
        <!-- 按钮 -->
        <div class="producer-head">
            <el-button type="primary" class="elbutton" @click="addFood = true">新增食品</el-button>
            <el-button type="danger" class="elbutton" @click="LoginOut">退出登录</el-button>
        </div>
        <!-- 主体 -->
        <div class="producer-cont">
            <!-- 数据表格 -->
            <div class="producer-table">
                <el-table :data="showData" style="width: 100%;" size="large" @sort-change="changeSort"
                    class="producer-table-cont">
                    <el-table-column header-align="center" align="center" prop="traceNumber" sortable="custom" label="溯源码" />
                    <el-table-column header-align="center" align="center" prop="name" label="食品名称" />
                    <el-table-column header-align="center" align="center" prop="from_address" label="生产商" />
                    <el-table-column header-align="center" align="center" prop="produce_time" sortable="custom" 
                        label="生产时间"></el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="producer-page">
                <el-pagination v-model:page-size="page_size" v-model:current-page="now_page" :page-sizes="sizes"
                    :default-page-size="sizes[0]" :background="false"
                    layout="total, sizes, prev, pager, next, jumper,slot" :total="productLegth">
                </el-pagination>
            </div>
        </div>
    </div>

    <!-- 新增食品弹出框 -->
    <el-dialog  class="producerDialog" v-model="addFood" title="新增食品" width="auto" align-center center :before-close="clearAddFood">
        <el-form :model="newFood">
            <el-form-item ref="formItemRef" label="溯源码" prop="code"
                :rules="[{ required: true, message: '请输入溯源码' }, { type: 'number', message: '请输入数字' }]"
                label-width="100px" label-position="left">
                <el-input v-model.number="newFood.code" />
            </el-form-item>

            <el-form-item ref="formItemRef1" label="食品名称" prop="name" :rules="{ required: true, message: '请输入食品名称' }"
                required label-width="100px" label-position="left">
                <el-input v-model="newFood.name" />
            </el-form-item>

            <el-form-item label="生产商" prop="producer"
                required label-width="100px" label-position="left">
                <el-input v-model="newFood.producer" disabled/>
            </el-form-item>

            <el-form-item ref="formItemRef3" label="质检情况" prop="quality" :rules="{ required: true, message: '请选择质检情况' }"
                required label-width="100px" label-position="left">
                <el-radio-group v-model="newFood.quality">
                    <el-radio value="1">优质</el-radio>
                    <el-radio value="2">合格</el-radio>
                    <el-radio value="3">不合格</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="clearAddFood">取消</el-button>
                <el-button type="primary" @click="ensureAddFood">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang='js' name=''>
import { ref, reactive, computed } from 'vue'
import { LoginOut } from '@/hooks/useLoginOut';
import strToTime from '@/utils/strToTime';
import getProducingAPI from '@/API/main/Producer/producing';
import getProduceAPI from '@/API/main/Producer/produce';
import showMessage from '@/utils/showMessage';

// 表格数据
const productData = ref([])
// 数据总长度
const productLegth = ref(0)
// 每次展示多少数据
const sizes = ref([10, 20, 50, 100])
// 当前每页展示条目
const page_size = ref(10)
// 当前页数
const now_page = ref(1)
// 载入食品
async function getProducing() {
    const res = await getProducingAPI()
    if (res) {
        productData.value = res.data
        showMessage("加载成功","success")
        // res.data.forEach(element => {
        //     productData.value.unshift(element)
        // });
        productLegth.value = productData.value.length
    }
}
getProducing()
const sortRule = ref(null)
const sortName = ref(null)
// 源数据排序
const sortData = computed(() => {
    if (productData.value) {
        if (sortRule.value == 1) {
            // console.log("升序")
            return productData.value.toSorted((a, b) => {
                // console.log(a[sortName.value] ," + ", b[sortName.value]," = ",a[sortName.value] - b[sortName.value])
                return a[sortName.value] - b[sortName.value]
            })
        } else if (sortRule.value == 2) {
            // console.log("降序")
            return productData.value.toSorted((a, b) => {
                return b[sortName.value] - a[sortName.value]
            })
        } else {
            // console.log("Ciallo~")
            return productData.value
        }
    } else { return null }
})

// 实际展示数据
const showData = computed(() => {
    // console.log(sortData.value)
    let vardata = ref(JSON.parse(JSON.stringify(sortData.value)).slice((now_page.value - 1) * page_size.value, now_page.value * page_size.value))
    vardata.value.forEach(element => {
        element["produce_time"] = strToTime(parseInt(element["produce_time"]))
    })
    return vardata.value
})
// 排序函数
function changeSort(e) {
    switch (e.order) {
        case "ascending": sortRule.value = 1; break;
        case "descending": sortRule.value = 2; break;
        default: sortRule.value = null; break;
    }
    if (e.order) {
        sortName.value = e.prop
    } else {
        sortName.value = null
    }
}
// 新增食品
let addFood = ref(false)
let formItemRef = ref()
let formItemRef1 = ref()
let formItemRef3 = ref()
let newFood = reactive(
    {
        code: "",
        name: "",
        producer: JSON.parse(localStorage.getItem("SLuserData"))?JSON.parse(localStorage.getItem("SLuserData"))["username"]:null,
        quality: ""
    }
)
function clearAddFood() {
    addFood.value = false
    newFood.code = ""
    newFood.name = ""
    newFood.quality = ""
    formItemRef.value.resetField();
    formItemRef1.value.resetField();
    formItemRef3.value.resetField();
}
function ensureAddFood() {
    const promises = [
        formItemRef.value.validate(),
        formItemRef1.value.validate(),
        formItemRef3.value.validate()
    ];

    Promise.all(promises)
        .then(() => {
            async function getProduce(foodName, traceName, traceNumber, quality) {
                const res = await getProduceAPI(foodName, traceName, traceNumber, quality)
                showMessage(res.data.msg, "success")
                clearAddFood()
                getProducing()
            }
            getProduce(newFood.name,JSON.parse(localStorage.getItem("SLuserData"))["username"], newFood.code, newFood.quality)
        })
        .catch((errors) => {
        });
}
</script>

<style scoped>
.producer-bg {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.producer-head {
    display: flex;
    justify-content: space-between;
}

.elbutton {
    width: 100px;
    height: 45px;
}

.producer-cont {
    width: 100%;
    height: 100%;
    margin-top: 20px;
    gap: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.producer-table {
    width: 100%;
    height: calc(100% - 110px);
    flex: 1;
}

.producer-table-cont {
    height: 100%;
    background: var(--Main_tableBG2);
    transition: all 0.5s;
}

.producer-page {
    height: 50px;
    flex: 1;
}
</style>
<style scoped>
.el-form {
    width: 500px;
    padding: 20px;
    padding-bottom: 0;
    margin-bottom: -20px;
}

.el-input {
    width: 100%;
}

.el-radio-group {
    width: 100%;
    display: flex;
    justify-content: space-around;
}

/* 底部框架 */
.dialog-footer {
    margin-top: 10px;
    display: flex;
    justify-content: space-around;
}

.dialog-footer .el-button {
    width: 30%;
    height: 40px;
}
</style>
<style>
.producerDialog{
    background: var(--Dialog_bg1);
    color: white;
}
.producerDialog .el-input *,.producerDialog>*>*{
    color: var(--Dialog_color);
}
</style>